package au.com.handsunited.web.controller.user;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import au.com.handsunited.model.User;
import au.com.handsunited.service.UserService;
import au.com.handsunited.web.session.SessionSupport;

/**
 *
 * @author arunda
 */
public class ProfileViewController extends AbstractController {


	private static Logger logger = LoggerFactory.getLogger(ProfileViewController.class);

	private UserService userService;
	private String successView;

	/**
	 *
	 */
	public ProfileViewController() {

	}

	/**
	 * @see org.springframework.web.servlet.mvc.AbstractController#handleRequestInternal(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String userIdStr = request.getParameter("id");

		User user = null;
		ModelAndView mav = null;
		Map<String, Object> model = new HashMap<String, Object>();

		if (StringUtils.isBlank(userIdStr)) {
			user = SessionSupport.getUser(request);
		} else {
			Long userId = Long.parseLong(userIdStr);
			user = userService.getUser(userId);
		}

		if (user != null) {
			model.put("entity", user);

			if ((SessionSupport.getUser(request) != null) && (SessionSupport.getUser(request).getId().equals(user.getId()))) {
				model.put("actionPendingGroupRelationships", user.getActionPendingGroupRelationships());
				model.put("actionPendingOrganisationRelationships", user.getActionPendingOrganisationRelationships());
				model.put("actionPendingProjectRelationships", user.getActionPendingProjectRelationships());
				model.put("actionPendingUserRelationships", user.getActionPendingUserRelationships());
			}
			mav = new ModelAndView(successView, model);
			SessionSupport.setCurrentlyActiveEntity(request, user);
		} else {
			ProfileViewController.logger.warn("Could not find user for id[{}]", userIdStr);
			// TODO what should the model and view be?
		}

		return mav;
	}






	/**
	 * @param userService the userService to set
	 */
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	/**
	 * @param successView the successView to set
	 */
	public void setSuccessView(String successView) {
		this.successView = successView;
	}

}
